package com.example.fragmentbrowser

import android.os.Bundle
import android.util.SparseArray
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import androidx.viewpager.widget.ViewPager
import com.google.android.material.tabs.TabLayout

class MainActivity : AppCompatActivity() {

    private lateinit var viewPager: ViewPager
    private lateinit var tabsPagerAdapter: PagerAdapter
    private lateinit var tabLayout: TabLayout

    private var mTestFragments: SparseArray<TestFragment> = SparseArray()
    private var key = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        viewPager = findViewById(R.id.viewPager)
        tabLayout = findViewById(R.id.tabLayout)
        tabsPagerAdapter = PagerAdapter(supportFragmentManager, mTestFragments)
        viewPager.adapter = tabsPagerAdapter
        tabLayout.setupWithViewPager(viewPager) // 将TabLayout与ViewPager关联

        findViewById<Button>(R.id.addTabButton).setOnClickListener {
            addNewTab()
        }
        mTestFragments.put(key++, TestFragment.newInstance("第一"))
    }

    private fun addNewTab() {
        if (tabsPagerAdapter.count < 3) { // 确保最多只有三个Tabs
            mTestFragments.put(key++, TestFragment.newInstance("第$key"))
            tabsPagerAdapter.notifyDataSetChanged() // 通知 ViewPager 数据已更改
            viewPager.currentItem = tabsPagerAdapter.count - 1 // 切换到新添加的Fragment
        }
    }

}
